import { createElement, HTMLAttributes, type FC } from 'react';
import classNames from 'classnames';

import { accordionDefaultProps } from './defaultProps';
import type { AccordionOptions } from './type';
import AccordionTitle from './AccordionTitle';
import AccordionContent from './AccordionContent';
import AccordionPanel from './AccordionPanel';
import { AccordionContextProvider } from './AccordionContext';

export interface AccordionProps extends AccordionOptions, HTMLAttributes<HTMLDivElement> {}

interface AccordionInterface extends FC<AccordionProps> {
  Title: typeof AccordionTitle;
  Content: typeof AccordionContent;
  Panel: typeof AccordionPanel;
}

const Accordion: AccordionInterface = (props) => {
  const {
    className,
    ui,
    defaultId,
    defaultIds,
    duration,
    styled,
    tree,
    fluid,
    inverted,
    compact,
    exclusive,
    children,
    forwardedRef,
    ...accordionProps
  } = props;

  return createElement(
    AccordionContextProvider,
    {
      initialValue: {
        activeId: defaultId,
        activeIds: defaultIds || [],
        prevId: defaultId,
        inTransition: false,
        duration,
        exclusive,
      },
    },
    createElement(
      'div',
      {
        ref: forwardedRef,
        className: classNames(
          { ui },
          styled,
          { styled, tree, fluid, inverted },
          compact,
          { compact },
          'accordion',
          className,
        ),
        style: { position: 'relative' },
        ...accordionProps,
      },
      children,
    ),
  );
};

Accordion.displayName = 'Accordion';
Accordion.defaultProps = accordionDefaultProps;

Accordion.Title = AccordionTitle;
Accordion.Content = AccordionContent;
Accordion.Panel = AccordionPanel;

export default Accordion;
